package com.xxx.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.xxx.user.domain.User;
import com.xxx.user.mapper.UserMapper;
import com.xxx.user.query.UserQuery;
import com.xxx.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> findAll() {
        List<User> list = userMapper.findAll();
        return list;
    }

    @Override
    public User findOne(Long id) {
        return userMapper.findOne(id);
    }

    @Override
    public List<User> findByPage(UserQuery userQuery) {
        PageHelper.startPage(userQuery.getCurrentPage(),userQuery.getPageSize());
        return userMapper.findByPage(userQuery);
    }

    @Override
    public void updateById(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void insert(User user) {
        try {
            String salt = RandomUtil.randomString(32);
            user.setSalt(salt);
            user.setPassword(SecureUtil.md5(user.getPassword()+salt));
            userMapper.insert(user);
        } catch (Exception e) {
            throw new RuntimeException("用户名已经存在");
        }
    }

    @Override
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public void bathUsers(Long[] ids) {
        userMapper.bathUsers(ids);
    }
}
